<?php

namespace app\v1\model;

use think\Model;
use think\Db;

/**
 * Class User
 * @package app\v1\model
 * 模块说明：所有的账号信息处理都在这个类里头处理
 */
class User extends Base
{
    //检查用户登录信息并且生成redis存储id以及
    public function checkLogin($userName,$password){
        $map['username']=$userName;
        $map['password']=md5($password);
        $userInfo=Db::name('users')->where($map)->find();
        if(!empty($userInfo)){
           $this->doLogin($userInfo);
        }else{
            renderInfo('4000002','账户名或密码错误');
        }
    }

    //登錄操作內容
    public function doLogin($userInfo){
        $openId=input('code');
        $data=array();
        $data['parentId']=$userInfo['id'];
        $data['userName']=$userInfo['username'];
        $data['name']=$userInfo['name'];
        $data['parent_token']=makeToken($userInfo['id'],$userInfo['password']);
        $data['avatar']=$userInfo['headimgurl'];
        $redis=getRedis();
        $redis->set(config('app.user_flag').$userInfo['id'],$data);
        $data['status']=$this->checkOpenId($userInfo['id'],$openId);
        renderData(0,'登录成功',$data);
    }

    //用户登录如果获取到的openid和账号绑定的openId不同要提示其切换绑定
    public function checkOpenId($userId,$openId){
            $map['pr.user_id']=$userId;
            $map['uw.openid']=$openId;
           $bandingOpenId=Db::name('Platform_relation')->alias('pr')->join('user_weixin uw','pr.platform_id=uw.id')->value('uw.openid');
           if($bandingOpenId==$openId){
               return 0;
           }else{
               $redis=getRedis();
               $redis->set('openId'.$userId,$openId);
               return 1;
           }

    }
    //更改用户和微信号的绑定
    public function changeBinding($userId,$openId){
            $map['effect']=1;
            $map['active']=1;
            $map['user_id']=$userId;
             $map2['openid']=$openId;
            $platformInfo=Db::name('Platform_relation')->where($map)->find();
            if(!empty($platformInfo)){
                $pmap['id']=$platformInfo['platform_id'];
                $pmap['effect']=1;
                $pmap['active']=1;
                $userWeixin=Db::name('User_weixin')->where($pmap)->find();
                if($userWeixin){
                    if($userWeixin['openid']!=$openId){

                        Db::startTrans();
                        try{
                            $rs1=Db::name('User_weixin')->where($map2)->setField('openid',uniqid());
                            $rs=Db::name('User_weixin')->where($pmap)->setField('openid',$openId);
                            Db::commit();
                            renderInfo(0,'切换绑定成功');
                        }catch (\Exception $e){
                            Db::rollback();
                            renderInfo(400008,'系统繁忙,请稍后重试');
                        }

                    }else{
                        renderInfo(0,'已经绑定无需切换');
                    }
                }else{
                    $wData=array();
                    $wData['openid']=$openId;
                    $wData['effect']=1;
                    $wData['active']=1;
                    $wData['append_time']=time();
                    $wData['modify_time']=time();
                    Db::startTrans();
                    try {
                        $rs1=Db::name('User_weixin')->where($map2)->setField('openid',uniqid());
                        $rs2 = Db::name('User_weixin')->insertGetId($wData);
                        Db::name('Platform_relation')->where($map)->setField('platform_id',$rs2);
                        Db::commit();
                        renderInfo(0,'切换绑定成功');
                    }catch (\Exception $e){
                        Db::rollback();
                        renderInfo(400008,'系统繁忙,请稍后重试');
                    }
                }
            }else{

                $wData=array();
                $wData['openid']=$openId;
                $wData['effect']=1;
                $wData['active']=1;
                $wData['append_time']=time();
                $wData['modify_time']=time();
//                $wData['nickname']=;
//                $wData['sex']=;
//                $wData['province']=;
//                $wData['city']=;
//                $wData['country']=;
//                $wData['headimgurl']=;
              //  $wData[]
                Db::startTrans();
                try{
                    $rs1=Db::name('User_weixin')->where($map2)->setField('openid',uniqid());
                    $prId=Db::name('User_weixin')->insertGetId($wData);
                    $data=array();
                    $data['effect']=1;
                    $data['active']=1;
                    $data['type']=1;
                    $data['platform_id']=$prId;
                    $data['user_id']=$userId;
                   $rs=Db::name('Platform_relation')->insert($data);
                   Db::commit();
                   renderInfo(0,'切换绑定成功');
                }catch (\Exception $e){
                   Db::rollback();
                   renderInfo(400008,'系统繁忙,请稍后重试');
                }
            }
    }
    //新的微信绑定逻辑
    public function changeBinding2($userId,$openId){

    }


    //通过微信的openid获取账号信息并且自动登录
    public function authMakeLogin($openId){
        $map['uw.openid']=$openId;
        $map['uw.effect']=1;
        $map['uw.active']=1;
        $map['pr.effect']=1;
        $map['pr.active']=1;

        $userId=Db::name('Platform_relation')->alias('pr')->join('user_weixin uw','pr.platform_id=uw.id')->where($map)->value('pr.user_id');
        if(!empty($userId)){
            $umap['id']=$userId;
            $umap['effect']=1;
            $umap['active']=1;
            $userInfo=Db::name('users')->where($umap)->find();
            if(!empty($userInfo)){
                $data=array();
                $data['parentId']=$userInfo['id'];
                $data['userName']=$userInfo['username'];
                $data['name']=$userInfo['name'];
                $data['parent_token']=makeToken($userInfo['id'],$userInfo['password']);
                $redis=getRedis();
                $redis->set(config('app.user_flag').$userInfo['id'],$data);
                $childId=$this->getDefaultChild($userId);
                $data['childId']=$childId;

                return $data;
            }
        }

        return false;
    }

    //默认选择一个孩子
    public function getDefaultChild($userId){
        $map['effect']=1;
        $map['active']=1;
        $map['parentid']=$userId;
        $childInfo=Db::name('Childcare_enroll')->where($map)->find();
        if(!empty($childInfo)){
            $this->getChildInfo($childInfo['orgid'],$childInfo['shopid'],$childInfo['studentid'],$childInfo['parentid'],1);
        }
        return $childInfo['studentid'];


    }

    /*
     * 获取全部的孩子列表
     * paramas $parentId(家长的Id)
     */


   /* public function getChildList($parentId){
        $map['uur.relation_user_id']=$parentId;
        $map['uur.effect']=1;
        $map['uur.active']=1;
       $childList=Db::name('User_user_relation')->alias('uur')->join('users u','uur.user_id=u.id')
           ->join('Student_infomation si','si.user_id=u.id')->join('org_user_relation our','uur.user_id=our.user_id')->join('org o','our.org_id=o.id')
           ->where($map)->field('u.id as userId,u.name,si.grade,si.school,u.headimgurl as avatar,o.name as orgName')->limit($this->pageCount)->page($this->currentPage)->select();
      $data=array('current_page'=>$this->currentPage,'childList'=>$childList);
       renderData(0,'ok',$data);
    }*/

   //切换机构学校或孩子列表
    public function getChildList($parentId){
        $map['ce.effect']=1;
        $map['ce.active']=1;
        $map['ce.parentid']=$parentId;
        $childList=Db::name('Childcare_enroll')->alias('ce')->join('org o','ce.orgid=o.id')->join('shop s','ce.shopid=s.id')
            ->join('users u','ce.studentid=u.id')->where($map)->distinct(true)->field('u.id as userId,u.name,u.headimgurl as avatar,o.name as orgName,s.name as school,o.id as orgId,s.id as shopId')->limit($this->pageCount)->page($this->currentPage)->select();
        $data=array('current_page'=>$this->currentPage,'childList'=>$childList);
        renderData(0,'ok',$data);
    }


    /*
     * 获取孩子账户信息
     * params$type=0:通常调用，1：默认选择孩子操作
     */
    public function getChildInfo($orgId,$shopId,$studentId,$parentId,$type=0){
            $res=$this->checkParentChild($studentId,$parentId);
            if(!$res){
                renderInfo(400006,'家长和孩子参数id错误');
            }
            //$educationInfo=$this->getEducationInfo($studentId);
            $childCareEnroll=$this->getChildCareEnrollInfo($orgId,$shopId,$studentId,$parentId);
           /* if(empty($educationInfo)){
               renderInfo(400005,'孩子还未绑定任何机构');
            }*/
            if(empty($childCareEnroll)){
                renderInfo(400005,'孩子还未绑定任何机构');
            }
            $childInfo=$this->getCommonInfo($studentId,(int)$childCareEnroll['orgid'],(int)$childCareEnroll['shopid']);
             if(!empty($childInfo)){
                $redis=getRedis();
               $userInfo=$redis->get(config('user_flag').$parentId);
               $userInfo['childId']=(int)$studentId;
               $userInfo['schoolId']=(int)$childCareEnroll['shopid'];
               $userInfo['orgId']=(int)$childCareEnroll['orgid'];
                $userInfo2=$redis->set(config('user_flag').$parentId,$userInfo);
                $childInfo['schoolId']=(int)$childCareEnroll['shopid'];
                $childInfo['orgId']=(int)$childCareEnroll['orgid'];
            }
            if($type==0){
                renderData(0,'ok',$childInfo);
            }

    }
    //获取孩子的资料信息
    public function getChildData(){
        $userInfo=getUserInfo();
        $map['id']=$userInfo['childId'];
        $childData=Db::name('Users')->where($map)->field('name as childName,sex,card_id as idNum')->find();
        renderData(0,'ok',$childData);
    }
    //检查孩子和家长的关系是否是对应的
    public function checkParentChild($studentId,$parentId){
            $map['relation_user_id']=$parentId;
            $map['user_id']=$studentId;
            $res=Db::name('User_user_relation')->where($map)->find();
            if($res){
                return true;
            }else{
                return false;
            }
    }

    //检查机构学校学生还有父母Id是否对应
    public function getChildCareEnrollInfo($orgId,$shopId,$studentId,$parentId){
        $map['effect']=1;
        $map['active']=1;
        $map['orgid']=$orgId;
        $map['studentid']=$studentId;
        $map['shopid']=$shopId;
        $map['parentid']=$parentId;
        $childCareEnrollInfo=Db::name('childcare_enroll')->where($map)->find();
        return $childCareEnrollInfo;

    }

    //通过孩子id获取孩子学校的信息
    public function getEducationInfo($studentId){
        $smap['user_id']=$studentId;
        $smap['sur.effect']=1;
        $smap['sur.active']=1;
        $educationInfo=Db::name('Shop_user_relation')->alias('sur')->join('shop s','s.id=sur.shop_id')->where($smap)->field('sur.shop_id,s.*')->find();

        return $educationInfo;
    }


    //获取公共孩子基本信息
    public function getCommonInfo($studentId,$orgId=0,$shopId=0){
        $map['u.id']=$studentId;
        $map['u.effect']=1;
        $map['u.active']=1;
        $childInfo=Db::name('Users')->alias('u')->join('Student_infomation si','si.user_id=u.id')->where($map)->field('u.id as childId,u.name,si.grade,si.school,u.headimgurl as avatar,si.class')->find();
        $childInfo['orgName']=$this->getOrgName($orgId);
        $childInfo['school']=$this->getSchoolName($shopId);
        return $childInfo;
    }

    //获取机构名称
    public function getOrgName($orgId){

        //$map['effect']=1;
        //$map['active']=1;
        $map['id']=$orgId;
        $orgName=Db::name('Org')->where($map)->value('name');
        return $orgName;
    }

    //获取校区名称

    public function getSchoolName($shopId){

       // $map['effect']=1;
       // $map['active']=1;
        $map['id']=$shopId;
        $shopName=Db::name('Shop')->where($map)->value('name');
        return $shopName;
    }

    //修改孩子资料信息
    public function editChildInfo($childName,$sex,$idNum){
        $userInfo=getUserInfo();
        checkSubmit($userInfo['parentId'],'editChildInfo');
        $map['id']=$userInfo['childId'];
        $data=array();
        $data['name']=$childName;
        $data['sex']=$sex;
        $data['modify_time']=time();
        $data['modify_user_id']=$userInfo['parentId'];
        $data['append_time']=time();
        $data['append_user_id']=$userInfo['parentId'];
        $data['card_id']=$idNum;
        $res=Db::name('Users')->alias('u')->where($map)->update($data);
        if(!empty($res)){
            renderInfo(0,'修改成功');
        }else{
            renderInfo(400008,'系统繁忙,稍后重试');
        }

    }

    //修改密码
    public function setPassword($oldPassword,$newPassword){
        if($oldPassword==$newPassword){
            renderInfo(400001,'新密码和旧密码不能一致');
        }
        $userInfo=getUserInfo();
        checkSubmit($userInfo['parentId'],'setPassword');
        $map['id']=$userInfo['parentId'];
        $dbPassword=Db::name('Users')->where($map)->value('password');
        if(md5($oldPassword)!=$dbPassword){
            renderInfo(400001,'旧密码错误');
        }
        $res=Db::name('Users')->where($map)->update(['password'=>md5($newPassword),'init_password'=>$newPassword]);
        if(!empty($res)){
            renderInfo(0,'密码修改成功');
        }else{
            renderInfo(400008,'系统繁忙,请稍后重试');
        }
    }

    //退出登录
    public function logout(){
        $userInfo=getUserInfo();
        $redis=getRedis();
        $res=$redis->set(config('user_flag').$userInfo['parentId'],array());
        if(!empty($res)){
            $map['user_id']=$userInfo['parentId'];
            $map['effect']=1;
            $map['active']=1;
            $platformId=Db::name('Platform_relation')->where($map)->value('platform_id');
            if(!empty($platformId)){
                $wmap['id']=$platformId;
                Db::name('User_weixin')->where($wmap)->setField('openid',uniqid());
            }
            renderInfo(0,'退出成功');
        }else{
            renderInfo(400008,'系统繁忙,请稍后重试');
        }
    }

    //个人中心页面接口
    public function userCenter(){
        $userInfo=getUserInfo();
        $childInfo=$this->getCommonInfo($userInfo['childId'],$userInfo['orgId'],$userInfo['schoolId']);
        $integral=model('v1/Integral');
        $integralInfo=$integral->getIntegralInfo($userInfo['childId']);
        $data=array('childInfo'=>$childInfo,'integralInfo'=>$integralInfo);
        renderData(0,'ok',$data);
    }

    //机构列表
    public function getOrgList($childId){
        $map['studentid']=$childId;
        $orgList=Db::name('childcar_enroll')->join('','org o')->where($map)->limit($this->pageCount)->page($this->currentPage)->select();
        $data=array('current_page'=>$this->currentPage,'orgList'=>$orgList);
        renderData(0,'ok',$data);
    }

    //获取校区列表
    public function schoolList($orgId){
        $map['org_id']=$orgId;
        $schoolList=Db::name('Shop')->where($map)->limit($this->pageCount)->page($this->currentPage)->select();
        $data=array('current_page'=>$this->currentPage,'orgList'=>$schoolList);
        renderData(0,'ok',$data);
    }

    //找回密码
    public function getForgetPassword($verifyCode,$phone,$newPassword){
        $this->checkVerifyCode($verifyCode,$phone);
        $data=array();
        $map['phone']=$phone;
        $data['password']=md5($newPassword);
        $res=Db::name('Users')->where($map)->update($data);
        if(!empty($res)){
            $redis=getRedis();
            $codeInfo=$redis->get(config('verify').$phone);
            $codeInfo['sendTime']=0;
            $redis->set(config('verify').$phone,$codeInfo);
            renderInfo(0,'重置密码成功');
        }else{
            renderInfo(400008,'系统繁忙,请稍后重试');
        }
    }
    //验证短信验证码是否正确
    public function checkVerifyCode($verifyCode,$phone){
        $redis=getRedis();
        $codeInfo=$redis->get(config('verify').$phone);
        if(time()-$codeInfo['sendTime']>300){
            renderInfo(400001,'验证码失效,请重新获取');
        }
        if($codeInfo['verifyCode']!=$verifyCode){
            renderInfo(4000001,'验证码错误');
        }
    }

    //验证码登录
    public function verifyCodeLogin($phone,$verifyCode){
        $this->checkVerifyCode($verifyCode,$phone);
        $map['phone']=$phone;
        $userInfo=Db::name('users')->where($map)->find();
        if(!empty($userInfo)){
            $this->doLogin($userInfo);
        }else{
            renderInfo('4000008','系統繁忙,請稍後重試');
        }
    }
    //获取用户的手机号码
    public function getUserPhone(){
        $userInfo=getUserInfo();
        $map['id']=$userInfo['parentId'];
        $phone=Db::name('Users')->where($map)->value('phone');
        return $phone;
    }



}
